﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using LxzhToast;

namespace AlarmClock
{
    public partial class FrmCountDown : Form
    {
        public DataBase database;
        private List<CountDown> countDownList;
        private List<LxzhTextBox> tbCountDownList;
        private int currentIndex;
        private bool addOrEdit = false;
        private Image[] closeBack = new Image[] { AlarmClock.Properties.Resources.close, AlarmClock.Properties.Resources.close_down };

        //无边窗体的拖动
        [DllImport("user32.dll")]  //需添加using System.Runtime.InteropServices
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;

        public FrmCountDown()
        {
            InitializeComponent();
        }

        private void CountDown_Load(object sender, EventArgs e)
        {
            this.Region = null;
            SetWindowRegion();
            initCountDownList(sender,e);
            if (!System.IO.File.Exists("Missing.wav"))
            {
                try
                {
                    System.IO.File.Copy(@"../../Resources/Missing.wav", "Missing.wav");
                }
                catch (Exception)
                {
                }
            }
            if (!System.IO.File.Exists("Bubble.wav"))
            {
                try
                {
                    System.IO.File.Copy(@"../../Resources/Bubble.wav", "Bubble.wav");
                }
                catch (Exception)
                {
                }
            }
        }

        private void CountDown_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }

        //绘制圆角
        public void SetWindowRegion()
        {
            System.Drawing.Drawing2D.GraphicsPath FormPath;
            FormPath = new System.Drawing.Drawing2D.GraphicsPath();
            Rectangle rect = new Rectangle(0, 2, this.Width, this.Height - 2);//this.Left-10,this.Top-10,this.Width-10,this.Height-10);                 
            FormPath = GetRoundedRectPath(rect, 10);
            this.Region = new Region(FormPath);
        }

        private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius)
        {
            int diameter = radius;
            Rectangle arcRect = new Rectangle(rect.Location, new Size(diameter, diameter));
            GraphicsPath path = new GraphicsPath();
            //   左上角   
            path.AddArc(arcRect, 180, 90);
            //   右上角   
            arcRect.X = rect.Right - diameter;
            path.AddArc(arcRect, 270, 90);
            //   右下角   
            arcRect.Y = rect.Bottom - diameter;
            path.AddArc(arcRect, 0, 90);
            //   左下角   
            arcRect.X = rect.Left;
            path.AddArc(arcRect, 90, 90);
            path.CloseFigure();
            return path;
        }

        private void cmsOperate_Opening(object sender, CancelEventArgs e)
        {
            try
            {
                LxzhTextBox currentBox = (LxzhTextBox)(sender as ContextMenuStrip).SourceControl;
                currentIndex = currentBox.Index;
                tsmEdit.Visible = true;
                tsmDelete.Visible = true;
                tsmDisplay.Visible = true;
            }
            catch (Exception)
            {
                currentIndex = -1;
                tsmEdit.Visible = false;
                tsmDelete.Visible = false;
                tsmDisplay.Visible = false;
            }
        }

        private void tsmAdd_Click(object sender, EventArgs e)
        {
            addOrEdit = true;
            plCountList.Visible = false;
            setTimeBox.Visible = true;
            setTimeBox.Text = "添加";
            btnCancel.Enabled = true;
            DateTime date = DateTime.Now;
            dateTP1.MinDate = date;
            dateTP1.Value = date;
            h1.Value = date.Hour;
            m1.Value = date.Minute;
            s1.Value = date.Second;
            tbLable1.Text = "";
        }

        private void tsmEdit_Click(object sender, EventArgs e)
        {
            addOrEdit = false;
            plCountList.Visible = false;
            setTimeBox.Visible = true;
            btnCancel.Enabled = true;
            setTimeBox.Text = "修改";
            DateTime date = countDownList[currentIndex].time;
            DateTime now=DateTime.Now;
            if (date < now)
            {
                dateTP1.MinDate = date;
            }
            else
            {
                dateTP1.MinDate = now;
            }
            dateTP1.Value= date;
            h1.Value = date.Hour;
            m1.Value = date.Minute;
            s1.Value = date.Second;
            tbLable1.Text = countDownList[currentIndex].lable;
        }

        private void tsmDelete_Click(object sender, EventArgs e)
        {
            if (currentIndex > -1)
            {
                database.deleteCountDown(currentIndex);
                int count = tbCountDownList.Count;
                for (int i = currentIndex+1; i < count; i++)
                {
                    tbCountDownList[i].Top -= 20;
                    tbCountDownList[i].Index -= 1;
                }
                plCountList.Controls.Remove(tbCountDownList[currentIndex]);
                tbCountDownList.RemoveAt(currentIndex);
                countDownList.RemoveAt(currentIndex);
                count--;
                if (count < 9)
                {
                    int width = plCountList.Width - 2;
                    for (int i = 0; i < count; i++)
                        tbCountDownList[i].Width = width;
                    if (count == 0)
                    {
                        dealNoCountDown();
                    }
                }
            }
        }

        private void tsmDisplay_Click(object sender, EventArgs e)
        {
            if (tbCountDownList[currentIndex].IsFinished)
            {
                Toast toast = new Toast(3, tbCountDownList[currentIndex].Label+" 已结束!");
                toast.Show();
            }
            else
            {
                FrmDisplayCountDown fdcd = new FrmDisplayCountDown(currentIndex, database);
                fdcd.Show();
            }
        }

        private void h1_ValueChanged(object sender, EventArgs e)
        {
            String t1Text = t1.Text.Substring(2, 6);
            t1.Text = (h1.Value < 10 ? ("0") : ("")) + h1.Value + t1Text;
        }

        private void m1_ValueChanged(object sender, EventArgs e)
        {
            if (m1.CarryOrBorrow == 1)
            {
                if (h1.Value == h1.Maximun)
                {
                    h1.CarryOrBorrow = 1;
                }
                else
                {
                    h1.CarryOrBorrow = 0;
                }
                h1.Value += Convert.ToDecimal(h1.Increment);
            }
            else if (m1.CarryOrBorrow == -1)
            {
                if (h1.Value == h1.Minimun)
                {
                    h1.CarryOrBorrow = -1;
                }
                else
                {
                    h1.CarryOrBorrow = 0;
                }
                h1.Value -= Convert.ToDecimal(h1.Increment);
            }
            String t1Text = t1.Text.Substring(2, 4);
            t1.Text = t1.Text.Replace(t1Text, (m1.Value < 10 ? (":0") : (":")) + m1.Value + ":");
        }

        private void s1_ValueChanged(object sender, EventArgs e)
        {
            if (s1.CarryOrBorrow == 1)
            {
                if (m1.Value == m1.Maximun)
                {
                    m1.CarryOrBorrow = 1;
                }
                else
                {
                    m1.CarryOrBorrow = 0;
                }
                m1.Value += Convert.ToDecimal(m1.Increment);
            }
            else if (s1.CarryOrBorrow == -1)
            {
                if (m1.Value == m1.Minimun)
                {
                    m1.CarryOrBorrow = -1;
                }
                else
                {
                    m1.CarryOrBorrow = 0;
                }
                m1.Value -= Convert.ToDecimal(m1.Increment);
            }
            String t1Text = t1.Text.Substring(0, 6);
            t1.Text = t1Text + (s1.Value < 10 ? ("0") : ("")) + s1.Value;
        }

        private void btnEnsure_Click(object sender, EventArgs e)
        {
            DateTime nowDate = dateTP1.Value;
            nowDate=nowDate.AddHours((int)h1.Value - nowDate.Hour);
            nowDate = nowDate.AddMinutes((int)m1.Value - nowDate.Minute);
            nowDate = nowDate.AddSeconds((int)s1.Value - nowDate.Second);
            if (addOrEdit)
            {
                int newIndex = 0;
                int count = countDownList.Count;
                for (int i = 0; i < count; i++)
                {
                    if (nowDate > countDownList[i].time)
                    {
                        newIndex++;
                    }
                    else
                    {
                        break;
                    }
                }
                database.addCountDownId(newIndex);
                database.addCountDown(newIndex,nowDate.Ticks + "", tbLable1.Text);
                countDownList.Insert(newIndex, new CountDown(nowDate, tbLable1.Text));
                if(count==0)
                    tbCountDownList = new List<LxzhTextBox>();
                insertCountDown(newIndex, sender, e);
            }
            else
            {
                //database.alterCountDown(currentIndex, nowDate.Ticks + "", tbLable1.Text);
                database.deleteCountDown(currentIndex);
                countDownList.RemoveAt(currentIndex);
                int newIndex = 0;
                int count=countDownList.Count;
                for (int i = 0; i < count; i++)
                {
                    if (nowDate > countDownList[i].time)
                    {
                        newIndex++;
                    }
                    else
                    {
                        break;
                    }
                }
                database.insertCountDown(newIndex, nowDate.Ticks + "", tbLable1.Text);
                countDownList.Insert(newIndex, new CountDown(nowDate, tbLable1.Text));
                refreshCountDownList(sender, e);
            }
            plCountList.Visible = true;
            setTimeBox.Visible = false;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            plCountList.Visible = true;
            setTimeBox.Visible = false;
        }

        private void btnClose_MouseHover(object sender, EventArgs e)
        {
            btnClose.BackgroundImage = closeBack[1];
        }

        private void btnClose_MouseDown(object sender, MouseEventArgs e)
        {
            btnClose.BackgroundImage = closeBack[1];
        }

        private void btnClose_MouseLeave(object sender, EventArgs e)
        {
            btnClose.BackgroundImage = closeBack[0];
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Dispose();
            this.Close();
        }

        public void initCountDownList(object sender, EventArgs e)
        {
            countDownList = database.getCountDownList();
            int count = countDownList.Count;
            int width = plCountList.Width - 2;
            if (count < 1)
            {
                dealNoCountDown();
            }
            else
            {
                if (count > 8)
                    width = plCountList.Width - 18;
                setTimeBox.Visible = false;
                tbCountDownList = new List<LxzhTextBox>();
                System.Drawing.Point point;
                DateTime dateTimeI;
                DateTime nowTime = DateTime.Now;
                LxzhTextBox tbCountDown;
                for (int i = 0; i < count; i++)
                {
                    dateTimeI = countDownList[i].time;
                    point = new Point(1, i * 20);
                    tbCountDown = new LxzhTextBox();
                    tbCountDown.Width = width;
                    tbCountDown.Height = 20;
                    tbCountDown.Label = countDownList[i].lable;
                    tbCountDown.Date = dateTimeI;
                    tbCountDown.Location = point;
                    plCountList.Controls.Add(tbCountDown);
                    if (i != countDownList[i].id)
                        database.alterCountDownId(countDownList[i].id, countDownList[i].lable, i);
                    tbCountDown.Index = i;
                    tbCountDown.ReadOnly = true;
                    tbCountDown.start(sender, e);
                    tbCountDown.ContextMenuStrip = this.cmsOperate;
                    tbCountDownList.Add(tbCountDown);
                }
            }
        }
        public void insertCountDown(int newIndex,object sender, EventArgs e)
        {
            int count = countDownList.Count;
            int width = plCountList.Width - 2;
            if (count > 8)
            {
                width = plCountList.Width - 18;
                for (int i = 0; i < count - 1; i++)
                    tbCountDownList[i].Width = width;
            }
            System.Drawing.Point point = new Point(1, (count-1) * 20);
            LxzhTextBox tbCountDown = new LxzhTextBox();
            tbCountDown.Width = width;
            tbCountDown.Height = 20;
            tbCountDown.Location = point;
            plCountList.Controls.Add(tbCountDown);
            tbCountDown.Index = count-1;
            tbCountDown.ReadOnly = true;
            tbCountDown.start(sender, e);
            tbCountDown.ContextMenuStrip = this.cmsOperate;
            tbCountDownList.Add(tbCountDown);
            for (int i = newIndex; i < count; i++)
            {
                tbCountDownList[i].Label = countDownList[i].lable;
                tbCountDownList[i].Date = countDownList[i].time;
                tbCountDownList[i].start(sender,e);
            }
        }

        public void refreshCountDownList(object sender, EventArgs e)
        {
            int count = countDownList.Count;
            if (count < 1)
                plCountList.Visible = false;
            else
            {
                DateTime nowTime = DateTime.Now;
                for (int i = 0; i < count; i++)
                {
                    tbCountDownList[i].Label = countDownList[i].lable;
                    tbCountDownList[i].Date = countDownList[i].time;
                    tbCountDownList[i].start(sender, e);
                }
            }
        }

        public int getIndex(object sender)
        {
            int count = tbCountDownList.Count;
            for (int i = 0; i < count; i++)
            {
                if ((LxzhTextBox)sender == tbCountDownList[i])
                    return i;
                else continue;
            }
            return -1;
        }
        private void dealNoCountDown()
        {
            plCountList.Visible = false;
            setTimeBox.Visible = true;
            addOrEdit = true;
            btnCancel.Enabled = false;
            DateTime now = DateTime.Now;
            dateTP1.MinDate = dateTP1.Value = now;
            h1.Value = now.Hour;
            m1.Value = now.Minute;
            s1.Value = now.Second;

        }
        private void Sort()
        {
            int count=countDownList.Count;
            DateTime[] times = new DateTime[count];
            for (int i = 0; i < count; i++)
            {
                times[i] = countDownList[i].time;
            }
            for (int i = 0; i < count; i++)
            {
                for (int j = count-1; j > i; j--)
                {
                    DateTime tempTime;
                    CountDown tempCountDown;
                    if (times[j] < times[j - 1])
                    {
                        tempTime = times[j];
                        tempCountDown = countDownList[j];
                        times[j] = times[j - 1];
                        countDownList[j] = countDownList[j - 1];
                        times[j - 1] = tempTime;
                        countDownList[j - 1] = tempCountDown;
                    }
                }
            }
        }
    }
}
